package cn.siriusbot.siriuspro.admin.webapi;

import cn.siriusbot.siriuspro.admin.service.ServerConfigService;
import cn.siriusbot.siriuspro.bot.application.SiriusApplicationInfo;
import cn.siriusbot.siriuspro.bot.plugin.PlugInClient;
import cn.siriusbot.siriuspro.bot.plugin.PlugInFactory;
import cn.siriusbot.siriuspro.bot.plugin.QuickPlugInClient;
import cn.siriusbot.siriuspro.config.Constant;
import cn.siriusbot.siriuspro.config.aop.PowerInterceptor;
import cn.siriusbot.siriuspro.error.MsgException;
import cn.siriusbot.siriuspro.web.R.R;
import com.alibaba.fastjson2.JSONObject;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;
import java.util.Objects;

/**
 * 快应用
 */
@RestController
@PowerInterceptor
@RequestMapping("/api/quick-app")
public class QuickAppController {

    @Autowired
    PlugInFactory plugInFactory;

    @Autowired
    ServerConfigService serverConfigService;

    private final String listUrl = Constant.FAST_APP_URL + "/api/quick/list";
    private final String infoUrl = Constant.FAST_APP_URL + "/api/quick/info";

    /**
     * HttpClient单例
     */
    public static final OkHttpClient httpClient = new OkHttpClient.Builder()
            .callTimeout(Duration.ofSeconds(10))     // 设置超时时间为10秒
            .build();


    /**
     * 获取快应用列表
     */
    @RequestMapping("/list")
    public R quickAppList() {
        // 获取依赖对象
        try {
            Request request = new Request.Builder()
                    .url(listUrl)
                    .get()
                    .build();
            Response response = httpClient.newCall(request).execute();
            String string = Objects.requireNonNull(response.body()).string();
            R r = JSONObject.parseObject(string, R.class);
            if (r.getCode() == 0) {
                if (r.getData() instanceof JSONObject list) {
                    list.forEach((key, val) -> {
                        if (val instanceof JSONObject json) {
                            SiriusApplicationInfo info = json.to(SiriusApplicationInfo.class);
                            String autoStart = serverConfigService.getString(info.getPackageName() + ".auto.start");

                            PlugInClient plugInClientBySessionId = plugInFactory.getPlugInClientByPackageName(info.getPackageName());
                            json.put("state", false);
                            json.put("autoStart", "true".equals(autoStart));
                            json.put("newVersion", info.getAppVersion());
                            if (plugInClientBySessionId != null) {
                                SiriusApplicationInfo localInfo = plugInClientBySessionId.getInfo();
                                json.put("state", true);
                                json.put("appVersion", localInfo.getAppVersion());
                            }
                        }
                    });
                }
            }
            return r;
        } catch (Throwable e) {
            e.printStackTrace();
            throw new MsgException(500, "获取快应用列表异常");
        }
    }

    @RequestMapping("/info/{appName}")
    public R quickInfo(@PathVariable("appName") String appName) {
        try {
            Request request = new Request.Builder()
                    .url(infoUrl + "/" + appName)
                    .get()
                    .build();
            Response response = httpClient.newCall(request).execute();
            String string = Objects.requireNonNull(response.body()).string();
            return JSONObject.parseObject(string, R.class);
        } catch (Throwable e) {
            e.printStackTrace();
            throw new MsgException(500, "获取快应用信息异常");
        }
    }

    @PostMapping("/auto-start")
    public R autoStart(
            String packageName,
            boolean auto
    ) {
        if (ObjectUtils.isEmpty(packageName)) {
            throw new MsgException(500, "应用名不能为空!");
        }
        serverConfigService.addConfig(packageName + ".auto.start", String.valueOf(auto));
        return new R()
                .setCode(0);
    }

    @PostMapping("/start")
    public R startQuickApp(
            String name,
            Boolean auto
    ) {
        QuickPlugInClient quickPlugInClient = new QuickPlugInClient(name, auto != null && auto);
        plugInFactory.add(quickPlugInClient);
        return new R()
                .setCode(0)
                .setMsg(String.format("启动快应用[%s]成功", quickPlugInClient.getInfo().getAppName()));
    }

    @PostMapping("/stop")
    public R stopQuickApp(
            String packageName
    ) {
        PlugInClient client = plugInFactory.getPlugInClientByPackageName(packageName);
        if (client == null) {
            throw new MsgException(500, "应用未启动!");
        }
        plugInFactory.exitApp(packageName);
        return new R()
                .setCode(0)
                .setMsg(String.format("退出快应用[%s]成功", client.getInfo().getAppName()));
    }


}
